package com.kgcx.organization.rabbitmq.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.client.order.pojo.Order;
import com.kgcx.common.rabbitmq.consts.QueueConst;
import com.kgcx.organization.domain.DriverMsg;
import com.kgcx.organization.domain.DriverMsgType;
import com.kgcx.organization.service.DriverMsgService;
import com.kgcx.organization.service.DriverService;

/**
 * 订单取消时状态变更
 */
@Component
public class DriverOrderCancelConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(DriverOrderCancelConsumer.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverMsgService driverMsgService;

    @RabbitListener(queues = QueueConst.DRIVER_ORDER_CANCEL, errorHandler = "custRabbitListenerErrorHandler")
    @Transactional(rollbackFor = Exception.class)
    public void precessUserStatus(String json) {
        LOG.info("收到订单取消的MQ消息。\n" + json);

        Order order = JSONObject.parseObject(json, Order.class);
        if (null == order.getDriverId()) {
            return;
        }

        addDriverMsg(order);

        driverService.orderCancelled(order.getDriverId());
    }

    private void addDriverMsg(Order order) {
        DriverMsg driverMsg = new DriverMsg();
        driverMsg.setIsRead(DriverMsg.UNREAD);
        driverMsg.setDriverId(order.getDriverId());
        driverMsg.setTypeId(DriverMsgType.ORDER);
        driverMsg.setTitle("您的订单已被取消");
        driverMsg.setContent("您的订单[" + order.getOrderNo() + "]已被乘客取消。");
        driverMsgService.addDriverMsg(driverMsg);
    }

}
